﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    /// <summary>
    /// 存档管理器
    /// 不能直接挂在场景中使用
    /// </summary>
    public class SaveManager : MonoSingleton<SaveManager>
    {
        private SaveBehaviour curSaveBehaviour;//当前存档行为
        private float lastWriteTime = -1;//上次保存时间
        private float writeInterval = 0.5f;//默认存档间隔为0.5秒
        /// <summary>
        /// 设置保存行为
        /// </summary>
        /// <param name="sb"></param>
        public void SetSaveBehaviour(SaveBehaviour sb,float writeInterval)
        {
            curSaveBehaviour = sb;
            curSaveBehaviour.Init();
            this.writeInterval = writeInterval;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        public void SaveData<T>(T data, bool saveImmediately = false) where T : SaveData<T>, new()
        {
            curSaveBehaviour.SaveData(data);
            curSaveBehaviour.IsDirty = true;
            if (saveImmediately)
                WriteToDisk();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T LoadData<T>() where T : SaveData<T>, new()
        {
            return curSaveBehaviour.LoadData<T>();
        }

        /// <summary>
        /// 写入磁盘
        /// </summary>
        public void WriteToDisk()
        {
            curSaveBehaviour.WriteToDisk();
            curSaveBehaviour.IsDirty = false;
        }

        private void Update()
        {
            if (curSaveBehaviour.IsDirty
                && Time.realtimeSinceStartup - lastWriteTime > writeInterval)
            {
                //默认一秒最大保存一次
                WriteToDisk();
                lastWriteTime = Time.realtimeSinceStartup;
                Debug.Log("SaveManager Auto Save");
            }
        }
    }

    /// <summary>
    /// 抽象数据类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class SaveData<T> where T : SaveData<T>, new()
    {
        /// <summary>
        /// 存档Key
        /// </summary>
        public abstract string SaveKey { get; }
        /// <summary>
        /// 获取默认值
        /// </summary>
        /// <returns></returns>
        public abstract T GetDefaultValue();
    }
}